export class AudioPlayer {
  audio: HTMLAudioElement | null = null;
  playing: boolean = false;
  // 监听是否已经添加了
  listenAdded: boolean = false;
  options: {
    id: string;
    /**
     * 音频文件地址
     */
    url: string;
    /**
     * 是否循环播放
     */
    loop: boolean;
    /**
     * 是否自动播放
     */
    autoplay: boolean;
    /**
     * 播放完毕回调
     */
    onEnded: () => void;
    /**
     * 开始播放回调
     */
    onPlay: () => void;
    /**
     * 暂停播放回调
     */
    onPause: () => void;
  };

  listenClick = () => {
    if (this.playing) return;
    this.audio?.play().catch((error) => {
      console.log(error);
    });
  };

  constructor(option: Partial<typeof AudioPlayer.prototype.options>) {
    this.options = Object.assign(
      {
        id: 'audio-player',
        url: '',
        loop: false,
        autoplay: false,
        onEnded: () => {},
        onPlay: () => {},
        onPause: () => {},
      },
      option,
    );
    if (document.getElementById(this.options.id)) {
      this.audio = document.getElementById(this.options.id) as HTMLAudioElement;
    } else {
      this.audio = new Audio();

      this.audio.id = this.options.id;
      this.audio.preload = 'auto';
      this.audio.autoplay = this.options.autoplay;
      this.audio.loop = this.options.loop;
      this.audio.src = this.options.url;
      this.audio.style.display = 'none';
      this.audio.addEventListener('ended', () => {
        this.options.onEnded();
      });
      this.audio.addEventListener('play', () => {
        this.playing = true;
        this.options.onPlay();
        // 删除监听
        if (this.listenAdded) {
          document.removeEventListener('touchstart', this.listenClick);
          document.removeEventListener('click', this.listenClick);
          this.listenAdded = false;
        }
      });
      this.audio.addEventListener('pause', () => {
        this.playing = false;
        this.options.onPause();
      });

      document.body.appendChild(this.audio);

      if (this.options.autoplay) {
        // 添加微信处理程序
        // wxAutoPlayReady(this.play.bind(this));
        // 监听用户点击事件后播放
        document.addEventListener('touchstart', this.listenClick);
        document.addEventListener('click', this.listenClick);
        this.listenAdded = true;
      }
    }
  }

  play(url?: string) {
    if (this.audio?.src === url) {
      return this.audio?.play();
    }
    if (this.audio) {
      this.audio.src = url || this.options.url;
    }
    this.audio?.play();
  }

  pause() {
    this.audio?.pause();
  }
}
